var express = require("express");
var router = express.Router();

const { getResult } = require("../../utils/sql");
const {
  getZhihuHot,
  getJueJinHot,
  getWeiboHot,
  getDoubanHot,
  getBilibiliList,
  getBaiduList,
  getHupuHotList,
  getHotList,
} = require("../../schedule/getHot");
const { transformTime } = require("../../utils/util");

const PLATFORM_MAP = {
  1: {
    handler: getZhihuHot,
  },
  2: {
    handler: getJueJinHot,
  },
  3: {
    handler: getWeiboHot,
  },
  4: {
    handler: getDoubanHot,
  },
  5: {
    handler: getBaiduList,
  },
  6: {
    handler: getBilibiliList,
  },
  7: {
    handler: getHupuHotList,
  },
};

async function getPlatformData(type, words) {
  const { handler } = PLATFORM_MAP[type] || {};
  if (handler) await handler();

  const sql = `SELECT * FROM platform_hot_today_list WHERE date=?
              ${type ? "AND platform_flag=?" : words ? "AND title LIKE ?" : ""} 
              ORDER BY rank`;

  const paramsList = type
    ? [new Date().toISOString().split("T")[0], Number(type)]
    : words
    ? [new Date().toISOString().split("T")[0], `%${words}%`]
    : [new Date().toISOString().split("T")[0]];
  return (await getResult({ sql, paramsList }))[0];
}

function processAllPlatforms(data) {
  const platforms = {
    7: "hupu",
    6: "bilibili",
    2: "juejin",
    5: "baidu",
    3: "weibo",
    1: "zhihu",
    4: "douban",
  };

  return Object.entries(platforms).reduce((acc, [flag, key]) => {
    const list = data.filter((item) => item.platform_flag === Number(flag));
    acc[key] = {
      list,
      updateTime: list[0] ? transformTime(list[0].create_time) : null,
    };

    return acc;
  }, {});
}

router.get("/list", async function (req, res) {
  const { type, hotWords } = req.query;
  const result = await getPlatformData(type, hotWords);
  console.log(result, "=====3333383");
  if (type && PLATFORM_MAP[type]) {
    res.send({
      code: 0,
      data: {
        list: result,
        updateTime: result[0] ? transformTime(result[0].create_time) : null,
      },
      message: "OK",
    });
  } else {
    res.send({
      code: 0,
      data: processAllPlatforms(result),
      message: "OK",
    });
  }
});

router.get("/list/refresh", async function (req, res) {
  await getHotList().then(async () => {
    const result = await getPlatformData();

    res.send({
      code: 0,
      data: processAllPlatforms(result),
      message: "OK",
    });
  });
});

module.exports = router;
